import 'dart:convert';
import 'dart:ui';

import 'package:enterprise_v6_app/app/core/constans/storage.dart';
import 'package:enterprise_v6_app/app/core/utils/storage_util.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';



abstract class AppLocaleUtil {
  // ignore: constant_identifier_names
  static const ZH_CN = Locale('zh', 'CN');

  // ignore: constant_identifier_names
  static const EN_US = Locale('en', 'US');

  static const Locale fallbackLocale = EN_US;

  static const List<Locale> supportedLocales = [ZH_CN, EN_US];

  static bool isZh(Locale? locale) {
    return locale != null && locale.languageCode.toLowerCase() == 'zh';
  }

  static bool isEn(Locale? locale) {
    return locale != null && locale.languageCode.toLowerCase() == 'en';
  }

  static bool isChinese() {
    return isZh(currentLocale);
  }

  static Future<void> init() async {
    await Future.wait(supportedLocales.map(_addLang));

    // 初始化
    currentLocale;
  }

  static Future<void> _addLang(Locale locale) async {
    final langUnderline = locale.toString();
    final langDash = locale.toLanguageTag();

    final jsonContent =
        await rootBundle.loadString('assets/lang/$langDash.json');
    final map = (json.decode(jsonContent) as Map).cast<String, String>();

    // 注意：key 值必须是下划线命名法，比如 'en_US'
    Get.addTranslations({langUnderline: map});
  }

  static Locale? _currentLocale;

  static Locale get currentLocale {
    if (_currentLocale == null) {
      final last = StorageUtil.getString(StorageConstants.appLanguage);
      if (last == null) {
        _currentLocale = isZh(Get.deviceLocale)
            ? ZH_CN
            : EN_US;

      } else {
        _currentLocale = last.toLowerCase() == ZH_CN.languageCode.toLowerCase()
            ? ZH_CN
            : EN_US;
      }
    }
    return _currentLocale ?? EN_US;
  }

  static int get  currentLocaleInt {
    int i = 1;
    i = supportedLocales.indexOf(currentLocale) + 1;
    return i;
  }

  static Future<Locale?> updateLang(Locale locale) async {
    final newLocale = locale;
    if (locale == currentLocale) {
      return null;
    }
    StorageUtil.setString(StorageConstants.appLanguage, locale.languageCode);
    _currentLocale = newLocale;
    await Get.updateLocale(newLocale);
    return newLocale;
  }
}
